#!/bin/sh
# vi: ts=4 noexpandtab

. /lib/cirros/shlib

write_lxc_is_container() {
	cat <<"EOF"
#!/bin/sh
# This program is written by /etc/rc.d/rc.sysinit.
# It simply reports whether or not this system is in an lxc container

EOF
	if is_lxc; then
		echo "# This is an LXC container"
		echo '[ "$1" = "-v" ] && echo '"$_LXC_CONTAINER"
		echo "exit 0"
	else
		echo "# This is NOT an LXC container"
		echo '[ "$1" = "-v" ] && echo none'
		echo "exit 1"
	fi
}

fail() { echo "FAIL:" "$@"; }
warn() { echo "WARN:" "$@"; }

### begin init ###

if [ ! -d /proc/1 ]; then
	mount -n -t proc /proc /proc || fail "failed mount /proc"
fi

read uptime cputime < /proc/uptime
iinfo "$0: up at $uptime"

if (: >/.testrw; ) >/dev/null 2>&1; then
	rm -f /.testrw
else
	mount -o remount,rw / || fail "failed mount / rw"
fi

is_mounted sysfs "" /sys ||
	mount -t sysfs sysfs /sys || fail "failed mount /sys!"

if ! is_lxc; then
	mount_once devtmpfs /dev /dev || fail "failed mount /dev"
fi
iinfo "container: $_LXC_CONTAINER"

mkdir -p /dev/pts /dev/shm /run

mount -a

mkdir /run/var.tmp

hostname -F /etc/hostname

f="/bin/lxc-is-container" && write_lxc_is_container > "$f" && chmod 755 "$f"

if ! is_lxc; then
	for d in $(awk '$2 == "/" { print $1 }' /proc/mounts); do
		[ -e "/dev/${d#/dev}" ] && ln -sf "${d#/dev/}" /dev/root && break
	done
fi

## pretend you're runlevel 3
set +f
for s in /etc/rc3.d/S*; do
	[ -x "$s" ] || continue
	"$s" "start" </dev/null || warn "$s failed"
done
set -f

if is_lxc; then
	grep -q "^pts/0$" /etc/securetty || echo "pts/0" >> /etc/securetty
	if ! [ /dev/tty1 -ef /dev/console ]; then
		# on libvirt lxc, /dev/console is a symlink to /dev/pts0
		# and /dev/tty1 is also a symlink to /dev/pts/0. So using
		# the tty1 gets us a getty on "console"
		#
		# on upstream lxc, /dev/console is a character device
		# so we run a getty there if so.
		lxc_console="console"
	fi
fi

s_args=""
for tty in $lxc_console tty1 ttyS0 hvc0 ttyAMA0; do
	if [ -e /dev/$tty ] && { echo "" >> "/dev/$tty" ; } 2>/dev/null ; then
		s_args="${s_args:+${s_args} }s/^#$tty:\(.*\)/$tty:\1/;"
	else
		s_args="${s_args:+${s_args} }s/^$tty:\(.*\)/#$tty:\1/;"
	fi
done
[ -z "$s_args" ] ||
	{ sed -i "$s_args" /etc/inittab && kill -HUP 1; }

if [ -f /etc/rc.local -a -x /etc/rc.local ]; then
	/etc/rc.local
fi
